package com.dy.lock.screen.component.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.ChatInfoComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.ChatInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.ChatService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.utils.DateUtil;
import com.dy.lock.screen.vo.ChatResultVo;
import com.dy.lock.screen.vo.ChatVo;
import com.google.gson.Gson;

@Component("chatInfoComponent")
public class ChatInfoComponentImpl implements ChatInfoComponent {
	private static final Logger log = Logger
			.getLogger(ChatInfoComponentImpl.class);
	private Gson gson;

	@Resource(name = "chatService")
	private ChatService chatService;

	public ChatInfoComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public boolean evaluateOrderForm(String body, Head head) {
		ChatVo vo = gson.fromJson(body, ChatVo.class);
		if (vo != null) {
			ChatInfo info = new ChatInfo();
			info.setOrderId(vo.getOrderId());
			info.setChatContent(vo.getEvaluation());
			info.setCustomerScore(vo.getRating());
			StringBuilder picPath = new StringBuilder();
			String base64Str = vo.getImage0();
			dealImg(vo, picPath, base64Str);
			base64Str = vo.getImage1();
			dealImg(vo, picPath, base64Str);
			base64Str = vo.getImage2();
			dealImg(vo, picPath, base64Str);
			String picPathStr = picPath.toString();
			if (StringUtils.isNotBlank(picPathStr)) {
				info.setChatPicPath(picPathStr.substring(0,
						picPathStr.length() - 1));
			}
			int re = this.chatService.save(info, head);
			if (re > 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",评价商品时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	private void dealImg(ChatVo vo, StringBuilder picPath, String base64Str) {
		String imgFilePath;
		File file = new File(CommonUtil.getPhotoLocation()
				+ Constant.USER_CHAT_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}
		if (StringUtils.isNotBlank(base64Str)) {
			imgFilePath = Constant.USER_CHAT_PATH + vo.getOrderId() + "_"
					+ DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_"
					+ CommonUtil.createRandomNumber() + ".jpg";
			if (StringUtils.isNotBlank(base64Str)) {
				picPath.append(imgFilePath);
				picPath.append(";");
				CommonUtil.saveBase64Image(base64Str, CommonUtil
						.getPhotoLocation()
						+ imgFilePath);
			}
		}
	}

	@Override
	public ChatResultVo getLastChatInfo(String body, Head head) {
		ChatVo vo = gson.fromJson(body, ChatVo.class);
		ChatResultVo reVo = new ChatResultVo();
		Integer count = 0;
		if (vo != null && StringUtils.isNotBlank(vo.getGoodsId())) {
			count = this.chatService.queryCountByGoodsId(vo.getGoodsId(), head);
			List<ChatVo> chatVos = new ArrayList<ChatVo>();
			List<ChatInfo> chatInfos = this.chatService.getLastChatInfo(vo
					.getGoodsId());
			for (ChatInfo chatInfo : chatInfos) {
				ChatVo chatVo = new ChatVo();
				if (StringUtils.isNotBlank(chatInfo.getHeaderPath())) {
					chatVo.setUserPhotoURL(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path.api")
							+ chatInfo.getHeaderPath());
				}
				chatVo.setUserId(chatInfo.getCustomerId());
				chatVo.setUserName(chatInfo.getCustomerName());
				chatVo.setDate(chatInfo.getPublishTime());
				chatVo.setScore(chatInfo.getCustomerScore());
				if (StringUtils.isNotBlank(chatInfo.getChatPicPath())) {
					String[] picList = chatInfo.getChatPicPath().split(";");
					StringBuilder builder = new StringBuilder();
					for (String picPath : picList) {
						builder.append(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ picPath + ";");
					}
					String pics = builder.toString();
					chatVo.setCmmentPicture(pics
							.substring(0, pics.length() - 1));
				}
				chatVo.setContent(chatInfo.getChatContent());
				chatVos.add(chatVo);
			}
			reVo.setChatList(chatVos);
			reVo.setTotalCount(count);
			return reVo;
		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",获取两条最新的商品评价时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public List<ChatVo> getAllChatInfo(String body, Head head) {
		ChatVo vo = gson.fromJson(body, ChatVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getGoodsId())) {
			List<ChatVo> chatVos = new ArrayList<ChatVo>();
			List<ChatInfo> chatInfos = this.chatService.getAllChatInfo(vo
					.getGoodsId());
			for (ChatInfo chatInfo : chatInfos) {
				ChatVo chatVo = new ChatVo();
				if (StringUtils.isNotBlank(chatInfo.getHeaderPath())) {
					chatVo.setUserPhotoURL(CommonUtil
							.getUrlPrefixApi("photo.url.prefix.path.api")
							+ chatInfo.getHeaderPath());
				}
				chatVo.setUserId(chatInfo.getCustomerId());
				chatVo.setUserName(chatInfo.getCustomerName());
				chatVo.setDate(chatInfo.getPublishTime());
				chatVo.setScore(chatInfo.getCustomerScore());
				if (StringUtils.isNotBlank(chatInfo.getChatPicPath())) {
					String[] picList = chatInfo.getChatPicPath().split(";");
					StringBuilder builder = new StringBuilder();
					for (String picPath : picList) {
						builder.append(CommonUtil
								.getUrlPrefixApi("photo.url.prefix.path.api")
								+ picPath + ";");
					}
					chatVo.setCmmentPicture(builder.toString());
				}
				chatVo.setContent(chatInfo.getChatContent());
				chatVos.add(chatVo);
			}
			return chatVos;
		} else {
			log
					.info("requestId:" + head.getRequestId()
							+ ",获取商品的所有评价时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
